package com.credithc.fastdfs.monitor.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.csource.common.MyException;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.StructGroupStat;
import org.csource.fastdfs.StructStorageStat;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.credithc.fastdfs.api.entity.Group;
import com.credithc.fastdfs.api.entity.GroupDay;
import com.credithc.fastdfs.api.entity.GroupHour;
import com.credithc.fastdfs.api.entity.Storage;
import com.credithc.fastdfs.api.entity.StorageDay;
import com.credithc.fastdfs.api.entity.StorageHour;
import com.credithc.fastdfs.api.mapper.GroupDayMapper;
import com.credithc.fastdfs.api.mapper.GroupHourMapper;
import com.credithc.fastdfs.api.mapper.GroupMapper;
import com.credithc.fastdfs.api.mapper.StorageDayMapper;
import com.credithc.fastdfs.api.mapper.StorageHourMapper;
import com.credithc.fastdfs.api.mapper.StorageMapper;
import com.credithc.fastdfs.monitor.service.AlarmInformService;
import com.credithc.fastdfs.monitor.service.FileDataService;
import com.credithc.fastdfs.monitor.service.JobService;
import com.credithc.fastdfs.util.FastdfsUtil;

@Service
public class JobServiceImpl implements JobService {

	private static final Logger logger = LoggerFactory
			.getLogger(JobServiceImpl.class);

	@Autowired
	private FileDataService fileDataService;
	@Autowired
	private GroupMapper groupMapper;

	@Autowired
	private GroupDayMapper groupDayMapper;
	@Autowired
	private GroupHourMapper groupHourMapper;
	@Autowired
	private StorageDayMapper storageDayMapper;
	@Autowired
	private StorageHourMapper storageHourMapper;
	@Autowired
	private StorageMapper storageMapper;
	
	@Resource(name = "alarmInformServiceImpl")
	private AlarmInformService alarmInformServiceImpl;
	
	Map<String, Date> datemap = new HashMap<String, Date>();

	@Override
	@Scheduled(cron = "55 0/1 * * * ?")
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateGroupByMinute() {
		logger.info("group minute data upate begin...");
		try {

			List<Group> groups = getGroupInfoByMinute();
			for (Group group : groups) {
				groupMapper.insert(group);
				for (Storage storage : group.getStorageList()) {
					if (null == storage.getCpu()) {
						storage.setCpu("0");
					}
					if (null == storage.getMem()) {
						storage.setMem(0.00);
					}
					storage.setGroupId(group.getGroupID());
					storageMapper.insert(storage);
					alarmInformServiceImpl.inform(storage);//告警校验
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("group minute data upated end");
	}

	@Override
	@Scheduled(cron = "0 55 0/1 * * ?")
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateGroupByHour() {
		logger.info("group hour data upate begin...");
		try {
			List<GroupHour> groups = getGroupInfoByHour();
			for (GroupHour group : groups) {
				groupHourMapper.insert(group);
				for (StorageHour storage : group.getStorageList()) {
					if (null == storage.getCpu()) {
						storage.setCpu("0");
					}
					if (null == storage.getMem()) {
						storage.setMem(0.00);
					}
					storage.setGroupId(group.getGroupHourID());
					storageHourMapper.insert(storage);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("group hour data upated end");
	}

	@Override
	@Scheduled(cron = "0 55 23 0/1 * ?")
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateGroupByDay() {
		logger.info("group day data upate begin...");
		try {
			List<GroupDay> groups = getGroupInfoByDay();
			for (GroupDay group : groups) {
				groupDayMapper.insert(group);
				for (StorageDay storage : group.getStorageList()) {
					if (null == storage.getCpu()) {
						storage.setCpu("0");
					}
					if (null == storage.getMem()) {
						storage.setMem(0.00);
					}
					storage.setGroupId(group.getGroupDayID());
					storageDayMapper.insert(storage);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("group day data upated end");
	}

	private List<Group> getGroupInfoByMinute() throws IOException, MyException {

		List<Group> result = new ArrayList<Group>();
		TrackerServer trackerServer = FastdfsUtil.getInstance()
				.getTrackerServer();
		if (trackerServer == null) {
			return result;
		}
		StructGroupStat[] groupStats = FastdfsUtil.getInstance()
				.getTrackerClient().listGroups(trackerServer);
		if (groupStats == null) {
			logger.error("ERROR! list groups error, error no: "
					+ FastdfsUtil.getInstance().getTrackerClient()
							.getErrorCode());
			return result;
		}
		for (StructGroupStat groupStat : groupStats) {
			Group group = new Group();
			BeanUtils.copyProperties(groupStat, group);
			StructStorageStat[] storageStats = FastdfsUtil.getInstance()
					.getTrackerClient()
					.listStorages(trackerServer, groupStat.getGroupName());
			for (StructStorageStat storageStat : storageStats) {
				Storage storage = new Storage();
				BeanUtils.copyProperties(storageStat, storage);
				storage.setCurStatus(ProtoCommon

				.getStorageStatusCaption(storageStat.getStatus()));
				storage.setGroup(group);
				storage.setGroupName(group.getGroupName());
				storage.setStorageID(UUID.randomUUID().toString()
						.replaceAll("-", ""));
				group.getStorageList().add(storage);
			}
			result.add(group);
		}

		Date date = new Date();
		for (Group group : result) {
			group.setCreated(date);
			group.setGroupID(UUID.randomUUID().toString().replaceAll("-", ""));
			for (Storage storage : group.getStorageList()) {
				storage.setCreated(date);
			}
		}

		FastdfsUtil.getInstance().closeTrackerServer(trackerServer);
		return result;
	}

	private List<GroupHour> getGroupInfoByHour() throws IOException,
			MyException {
		List<GroupHour> result = new ArrayList<GroupHour>();
		TrackerServer trackerServer = FastdfsUtil.getInstance()
				.getTrackerClient().getConnection();
		if (trackerServer == null) {
			return result;
		}
		StructGroupStat[] groupStats = FastdfsUtil.getInstance()
				.getTrackerClient().listGroups(trackerServer);
		if (groupStats == null) {
			logger.error("ERROR! list groups error, error no: "
					+ FastdfsUtil.getInstance().getTrackerClient()
							.getErrorCode());
			return result;
		}

		for (StructGroupStat groupStat : groupStats) {
			GroupHour group = new GroupHour();
			group.setCreated(new Date());
			group.setGroupHourID(UUID.randomUUID().toString()
					.replaceAll("-", ""));
			BeanUtils.copyProperties(groupStat, group);
			StructStorageStat[] storageStats = FastdfsUtil.getInstance()
					.getTrackerClient()
					.listStorages(trackerServer, groupStat.getGroupName());
			for (StructStorageStat storageStat : storageStats) {
				StorageHour storage = new StorageHour();
				storage.setCreated(new Date());
				storage.setStorageHourID(UUID.randomUUID().toString()
						.replaceAll("-", ""));
				BeanUtils.copyProperties(storageStat, storage);
				storage.setCurStatus(ProtoCommon
						.getStorageStatusCaption(storageStat.getStatus()));
				storage.setGroup(group);
				storage.setGroupName(group.getGroupName());
				group.getStorageList().add(storage);
			}
			result.add(group);
		}
		FastdfsUtil.getInstance().closeTrackerServer(trackerServer);
		return result;
	}

	private List<GroupDay> getGroupInfoByDay() throws IOException, MyException {
		List<GroupDay> result = new ArrayList<GroupDay>();
		TrackerServer trackerServer = FastdfsUtil.getInstance()
				.getTrackerServer();
		if (trackerServer == null) {
			return result;
		}
		StructGroupStat[] groupStats = FastdfsUtil.getInstance()
				.getTrackerClient().listGroups(trackerServer);
		if (groupStats == null) {
			logger.error("ERROR! list groups error, error no: "
					+ FastdfsUtil.getInstance().getTrackerClient()
							.getErrorCode());
			return result;
		}
		for (StructGroupStat groupStat : groupStats) {
			GroupDay group = new GroupDay();
			group.setCreated(new Date());
			group.setGroupDayID(UUID.randomUUID().toString()
					.replaceAll("-", ""));
			BeanUtils.copyProperties(groupStat, group);
			StructStorageStat[] storageStats = FastdfsUtil.getInstance()
					.getTrackerClient()
					.listStorages(trackerServer, groupStat.getGroupName());
			for (StructStorageStat storageStat : storageStats) {
				StorageDay storage = new StorageDay();
				storage.setCreated(new Date());
				storage.setStorageDayID(UUID.randomUUID().toString()
						.replaceAll("-", ""));
				BeanUtils.copyProperties(storageStat, storage);
				storage.setCurStatus(ProtoCommon
						.getStorageStatusCaption(storageStat.getStatus()));
				storage.setGroupDay(group);
				storage.setGroupName(group.getGroupName());
				group.getStorageList().add(storage);
			}
			result.add(group);
		}
		FastdfsUtil.getInstance().closeTrackerServer(trackerServer);
		return result;
	}
}
